<template>
  <div class="contract-recycle-wrap">
    <div v-if="isEdit" class="edit">
      <up-attachment
        :import-api="'/common/file/upload'"
        :hide-confirm="true"
        :file-list="contractRecycle"
        :limit="10"
        :is-review="canCheck"
        btn-text="上传文件"
        style="max-width: 240px;width: calc(100% - 60px);"
        @complateSetData="complateSetData($event)"
        @removeFileList="removeFileList($event)"
      />
      <span class="edit-btn" style="height: 32px; line-height: 32px;" @click="submit">提交</span>
      <span class="edit-btn cancle-btn" style="height: 32px; line-height: 32px;" @click="cancle">取消</span>
    </div>
    <div v-else class="check">
      <div class="status-box">
        <span class="status">{{ contractRecycle && contractRecycle.length > 0 ? '已回收' : '未回收' }}</span>
        <span v-if="canModify" class="edit-btn" @click="modify">
          {{ contractRecycle && contractRecycle.length > 0 ? '修改附件' : '上传' }}
        </span>
      </div>
      <div v-if="contractRecycle && contractRecycle.length > 0" :class="{'mobile-file-container': showMobilePage}" class="file-container">
        <div v-for="(item, index) in contractRecycle" :key="index" class="file-item">
          <i class="el-icon-document"/>
          <el-tooltip class="item" placement="top" effect="dark">
            <div slot="content" style="max-width: 200px;">
              <div>文件名：{{ item.name }}</div>
              <div v-if="item.time">上传时间：{{ item.time | format('YYYY-MM-DD HH:mm:ss') }}</div>
            </div>
            <div class="name">{{ item.name }}</div>
          </el-tooltip>
          <div v-if="canCheck" class="button-text" style="margin-left:10px;" @click="downloadFile(item.url, item.name)">预览</div>
          <div v-if="canCheck" class="button-text" style="margin-left:10px;" @click="downloadFile(item.url, item.name, true)">下载</div>
          <!-- <i v-if="!isDisabled" class="icon el-icon-close" @click="removeFile(item, index)" /> -->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import upAttachment from '@/components/Common/upAttachment/index';
import { contractRecycleApi } from '@/api/legal';
import { hasRouteAuth } from '@/utils/permission';
import { downloadFile } from '@/utils';
import { format } from '@/filters/date';
import { decrypt, openNewWindow } from '@/utils';
import { mapState } from 'vuex';

export default {
  name: 'ContractRecycle',
  filters: { format },
  components: {
    upAttachment
  },
  props: {
    contractId: {
      type: Number,
      default: null
    },
    params: {
      type: Array,
      default: () => {
        return [];
      }
    },
    modifyAuth: {
      type: String,
      default: ''
    },
    checkAuth: {
      type: String,
      default: ''
    },
    setEvents: {
      type: Array,
      default: () => {
        return [];
      }
    },
    processStatus: {
      type: Number,
      default: null
    },
    isCurrentVersion: {// 是否当前版本
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      contractRecycle: [],
      isEdit: false,
      cacheFile: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    selectData: {
      get() {
        return this.params;
      },
      set(val) {
        this.$emit('change', val);
      }
    },
    canCheck() {
      return this.processStatus === 4 && this.hasRouteAuth(this.checkAuth) || this.processStatus === 1 && this.hasRouteAuth(this.checkAuth) && this.setEvents && this.setEvents.includes(1);
    },
    canModify() {
      if (!this.isCurrentVersion) { return false; }
      if (this.processStatus === 1) {
        if (this.setEvents && this.setEvents.includes(1) && this.hasRouteAuth(this.modifyAuth)) {
          return true;
        } else {
          return false;
        }
      } else if (this.processStatus === 4) {
        if (this.hasRouteAuth(this.modifyAuth) && this.hasRouteAuth(this.checkAuth)) {
          return true;
        } else {
          return false;
        }
      }
      return false;
    }
  },
  watch: {
    params: {
      handler(val) {
        this.contractRecycle = val || [];
      },
      immediate: true
    }
  },
  methods: {
    hasRouteAuth,
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      this.contractRecycle.push(fileList);
      this.$emit('complateSetData');
    },
    removeFileList({ file, index }) {
      this.contractRecycle.splice(index, 1);
      this.$emit('removeFile');
    },
    submit() {
      if (!(this.contractRecycle && this.contractRecycle.length > 0)) {
        this.$message({
          type: 'warning',
          message: '请上传合同回收附件'
        });
        return;
      }
      const param = {
        id: Number(decrypt(this.$route.params.id)),
        attachment: this.contractRecycle
      };
      contractRecycleApi(param).then(res => {
        if (res.code === 200) {
          this.isEdit = false;
          this.$message({
            type: 'success',
            message: '提交成功'
          });
        }
      });
    },
    modify() {
      this.isEdit = true;
      this.cacheFile = JSON.parse(JSON.stringify(this.contractRecycle));
    },
    cancle() {
      this.contractRecycle = this.cacheFile;
      this.isEdit = false;
    },
    downloadFile(url, name, download = false) {
      if (!this.canCheck) {
        return;
      }
      if (download) {
        downloadFile(url, name);
        return;
      }
      const img = /(\.(gif|png|jpg|jpeg|webp|bmp|tif|pdf))$/i;
      if (img.test(name)) {
        window.open(url);
      } else if (this.isExcel(name)) {
        this.viewExcel(url, name);
      } else {
        downloadFile(url, name);
      }
    },
    isExcel(name) {
      const excel = /(\.(doc|docx|xls|xlsx|xlsm|ppt|pptx|txt))$/i;
      return excel.test(name);
    },
    viewExcel(url, name) {
      try {
        // const hangzi = /[\u4e00-\u9fa5]+/g;
        // name = name.replace(hangzi, 'a');
        const timestamp = (new Date()).valueOf();
        const random = Math.ceil(Math.random() * 10);
        const lists = name.split('.');
        const fileName = `${timestamp}${random}.` + lists[lists.length - 1];
        const previewUrl = `${url}#&fullfilename=${fileName}`;
        const officeUrl = 'http://fileview.feibo.com/onlinePreview?url=' + encodeURIComponent(btoa(previewUrl));
        // window.open(officeUrl, '_blank');
        openNewWindow(officeUrl);
      } catch (error) {
        console.log(error);
        this.dinkDownload(url, name);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.edit-btn {
  margin-left: 10px;
  cursor: pointer;
  font-weight: bold;
  color: #406EFF;
  flex-shrink: 0;
}
.cancle-btn {
  color: #192452;
}
.status-box, .edit {
  display: flex;
}
.file-container {
  margin-top: 10px;
  width: 100%;
  max-width: 300px;
  .file-item {
    align-items: center;
    display: flex;
    padding: 0 5px;
    border-radius: 3px;
    .el-icon-document {
      font-size: 14px;
      margin-right: 5px;
      color: #909399;
    }
    .icon {
      font-size: 14px;
      color: #999;
      cursor: pointer;
      display: none;
    }
    .name {
      font-size: 13px;
      color: #333;
      flex:1;
      line-height: 2;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 85%;
      &.disabled {
        cursor: not-allowed;
      }
    }
    &:hover {
      background-color: #f5f7fa;
      .name {
        color: #406EFF;
      }
      .icon {
        display: block;
      }
    }
  }
}
.mobile-file-container {
  width: 200px;
}
</style>
